<template>
	<view class="loginPage">
		<view class="loginTop">
			为您提供更多
			<text style="color: #588bf3">健康</text>
			服务
		</view>
		<view class="loginTop">
			提供
			<text style="color: #588bf3">更全面</text>
			的服务，值得您的期待
		</view>
		<img
			style="width: 444rpx; height: 668rpx"
			src="https://oneredhealth.oss-cn-hangzhou.aliyuncs.com/2023/10/13/c1cd8c3f37244b63815adbe23899b13a.png"
			alt="图片"
		/>
		<view class="loginBox">
			<u-button
				text="登录"
				shape="circle"
				color="#588bf3"
				:customStyle="loginButtonCustomStyle"
				@click="add"
				v-if="mobile || !isread.length"
			/>
			<u-button
				v-if="!mobile && isread.length"
				text="登录"
				shape="circle"
				color="#588bf3"
				openType="getPhoneNumber"
				:customStyle="loginButtonCustomStyle"
				@getphonenumber="getphonenumberHander"
			/>
			<u-button
				text="取消登录"
				shape="circle"
				color="#DBDBDB"
				:customStyle="loginButtonCustomStyle"
				@click="goTo"
			/>
			<u-checkbox-group
				v-model="isread"
				@change="checkboxChange"
			>
				<view class="check">
					<u-checkbox
						name="read"
						shape="circle"
					/>
					<text class="text">我已阅读并同意</text>
					<text
						class="text xieyiColor"
						@click="toUserAgreement('OX_MAN_USER_PROTOCOL')"
					>
						《用户协议》
					</text>
					<text class="text">和</text>
					<text
						class="text xieyiColor"
						@click="toUserAgreement('OX_MAN_PRIVACY_AGREEMENT')"
					>
						《隐私政策》
					</text>
				</view>
			</u-checkbox-group>
			<privacySet
				ref="privacy"
				@initData="init"
				@initSetting="initSetting"
			></privacySet>
		</view>
	</view>
</template>

<script>
	import privacySet from "@/components/privacySet"
	import { getCustomerPhoneNumberWithAppId, loginSalesmanTokenByPhoneWithToken, login, getCustomerInfoByToken } from "@/api/login.js"
	import { appIdCard } from "@/api/card"
	import { getOpenId } from "@/api/userSalesman.js"
	export default {
		components: {
			privacySet
		},
		data() {
			return {
				loginButtonCustomStyle: {
					width: "446rpx",
					height: "90rpx",
					fontSize: "36rpx",
					marginBottom: "40rpx"
				},
				isread: [],
				mobile: "",
				isLogin: false,
				otherBool: false
			}
		},
		created() {
			let that = this
			// 获取 用户是否授权过手机号 授权过就不用授权手机号直接登录了
			const appId = uni.getAccountInfoSync().miniProgram.appId
			uni.login({
				provider: "weixin",
				success: (loginRes) => {
					this.loginRes = loginRes
					that.$store.commit("SET_LOGIN_CODE", loginRes.code)
					login(
						{
							code: loginRes.code,
							appId
						},
						{
							auth: true
						}
					)
						.then(async (res) => {
							// 先登录 第一步 获取客户 token
							await that.$store.commit("SET_TOKEN", res.data.access_token)
							await that.$store.commit("SET_TOKEN_CUSTOMER", res.data.access_token)
							await getCustomerInfoByToken().then((res) => {
								that.mobile = res.data.mobile
							})
						})
						.finally(() => {
							that.buttonLoading = false
						})
				}
			})
		},
		methods: {
			toUserAgreement(code) {
				uni.navigateTo({
					url: "/pages/agreement/userAgreement/index?code=" + code
				})
			},
			init(b) {
				this.isLogin = b
				//  b true 同意 false 拒绝
				if (b) {
					this.isread = ["read"]
				} else {
					this.isread = []
				}
			},
			initSetting(b) {
				this.otherBool = b
			},
			checkboxChange(n) {
				if (n.length) this.$refs.privacy.getPrivacySet()
			},
			add() {
				if (!this.isread.length) {
					return uni.showToast({
						title: "请阅读并勾选协议",
						icon: "none"
					})
				}
				if (this.otherBool || (!this.otherBool && this.isLogin)) this.loginFun()
			},
			getphonenumberHander(e) {
				const that = this
				if (e.detail.errMsg === "getPhoneNumber:fail user deny") return
				// $tendId 获取
				let appId = '';
				// 平台判断，只有在小程序环境才调用uni.getAccountInfoSync
				const platform = uni.getSystemInfoSync().platform.toLowerCase();
				if (platform === 'devtools' || platform === 'ios' || platform === 'android') {
					try {
						appId = uni.getAccountInfoSync()?.miniProgram?.appId || '';
					} catch (error) {
						console.log('获取appId失败:', error);
						appId = '';
					}
				}
				appIdCard(appId).then((res) => {
					res.data && that.$store.commit("SET_TENDID", res.data)
				})
				let params = {
					code: e.detail.code,
					encryptedData: e.detail.encryptedData,
					iv: e.detail.iv,
					appId
				}
				getCustomerPhoneNumberWithAppId(params).then(async (result) => {
					// code 200 data.access_token  有就是业务员
					// data.access_token 为空 就是客户端 customer
					const authority = result.data.access_token ? "salesman" : "customer"
					// 授权者的 角色
					await that.$store.commit("SET_AUTHORITY", authority)
					// 是业务员 直接返回业务员token 再覆盖一遍登录的时候客户的token
					if (result.data.access_token) {
						await that.$store.commit("SET_TOKEN", result.data.access_token) //更新login_code
						uni.login({
							provider: "weixin",
							success: (codeRes) => {
								this.codeRes = codeRes
								getOpenId({
									code: codeRes.code
								})
								that.$store.commit("SET_LOGIN_CODE", codeRes.code)
							}
						})
					}
					await that.$store.dispatch("USERINFO", { $u: uni.$u })
					let url = "/pages/counselling/index"
					const loginBackUrl = uni.getStorageSync("loginBackUrl")
					if (loginBackUrl) url = loginBackUrl
					const loginBackUrlOption = uni.getStorageSync("loginBackUrlOption") || {}
					if (url === "/pages/counselling/index") {
						that.$store.commit("SET_CURRENT_TAB_INDEX", 0)
						uni.reLaunch({
							url: "/pages/counselling/index"
						})
					} else {
						uni.$u.route({
							type: "reLaunch",
							url,
							params: loginBackUrlOption
						})
					}
				})
			},
			loginFun() {
				let that = this
				loginSalesmanTokenByPhoneWithToken().then(async (result) => {
					// code 200 data.access_token  有就是业务员
					// data.access_token 为空 就是客户端 customer
					const authority = result.data.access_token ? "salesman" : "customer"
					// 授权者的 角色
					await that.$store.commit("SET_AUTHORITY", authority)
					// 是业务员 直接返回业务员token 再覆盖一遍登录的时候客户的token
					if (result.data.access_token) {
						await that.$store.commit("SET_TOKEN", result.data.access_token) //更新login_code
						uni.login({
							provider: "weixin",
							success: (codeRes) => {
								this.codeRes = codeRes
								getOpenId({ code: codeRes.code })
								// 保存code
								that.$store.commit("SET_LOGIN_CODE", codeRes.code)
							}
						})
					}

					// that.$store.dispatch("USERINFO", { $u: uni.$u })
					// that.$store.commit("SET_CURRENT_TAB_NAME", 0)
					// uni.reLaunch({
					// 	url: "/pages/counselling/index"
					// })
					await that.$store.dispatch("USERINFO", { $u: uni.$u })
					let url = "/pages/counselling/index"
					const loginBackUrl = uni.getStorageSync("loginBackUrl")
					if (loginBackUrl) url = loginBackUrl
					const loginBackUrlOption = uni.getStorageSync("loginBackUrlOption") || {}
					console.log("登录页", loginBackUrl)
					if (url === "/pages/counselling/index") {
						that.$store.commit("SET_CURRENT_TAB_INDEX", 0)
						uni.reLaunch({
							url: "/pages/counselling/index"
						})
					} else {
						uni.$u.route({
							type: "reLaunch",
							url,
							params: loginBackUrlOption
						})
					}
				})
			},
			// 取消登录
			goTo() {
				uni.navigateBack()
			}
		}
	}
</script>

<style lang="scss">
	.loginPage {
		width: 100vw;
		height: 100vh;
		background-size: 130vw;
		background-repeat: no-repeat;
		background-position: top center;
		display: flex;
		align-items: center;
		flex-direction: column;
		background-color: #fff;
		font-size: 32rpx;
		color: #3d3d3d;
		padding-top: 60rpx;

		.loginTop {
			margin-bottom: 30rpx;
		}

		.loginBox {
			width: 100vw;
			display: flex;
			flex-direction: column;
			justify-content: center;

			.check {
				width: 100%;
				display: flex;
				justify-content: center;
				align-items: center;
				margin-top: 40rpx;

				.text {
					font-size: 28rpx;
					color: #3d3d33;
				}

				.xieyiColor {
					color: $uni-color-primary !important;
				}
			}
		}

		.check {
			width: 100%;
			display: flex;
			justify-content: center;
			align-items: center;
			margin-top: 40rpx;

			.text {
				font-size: 28rpx;
				color: #3d3d33;
			}

			.xieyiColor {
				color: $uni-color-primary !important;
			}
		}
	}
</style>
